<!-- 素材选择 -->
<template>
  <BasicModal 
    v-bind="$attrs" 
    @register="registerModal" 
    :title="title" width="1200px" 
    @ok="handleSubmit" 
    :draggable="false"
    destroy-on-close
  >
    <PageWrapper :sidebarWidth="230" ref="contentElRef">
      <template #sidebar>
        <MyTreeSelect 
          v-bind="treeProps" 
          @select="onTreeSelect" 
          ref="materialGroupTreeRef"
          @add-child="handleAddGroup"
          @edit="handleEditGroup"
        />
      </template>
      <!-- 
        这里必须定义的class且必须为命名空间 + basic-table,
        因为PageWrapper组件内部是根据查找 该css类选择器定位到具体元素(const table = el.querySelector(`.${namespace}-basic-table`);)
        然后计算高度的, 如果不把 标签和表格用 `${namespace}-basic-table` 类选择器包裹,
        会出现侧边栏高度问题
        -->
      <div :class="`${namespace}-basic-table`">
        <a-tabs :defaultActiveKey="MaterialType.IMAGE.type" v-if="!materialType" 
          @change="handleChange"
        >
          <a-tab-pane 
            v-for="item in MaterialType" 
            :tab="item.name" :key="item.type" 
            force-render
          />
        </a-tabs>
        <MaterialList 
          :groupId="materialGroupId" 
          :materialType="activeMaterialType" @open-group="handleOpenGroup"
          @select-change="handleSelectChange" 
          :selectCount="selectCount" :isSelectModel="true" 
        />
      </div>

      <MeterialGroupModal @register="registerMeterialGroup" @success="handleSaveOrUpdateGroupSuccess" />
    </PageWrapper>
  </BasicModal>
</template>
<script lang="ts" setup>
import { 
  ref, computed, unref, nextTick, onMounted,
  watchEffect, provide, onUnmounted 
} from 'vue';
import { useDesign } from '/@/hooks/web/useDesign'
import { BasicModal, useModalInner } from '/@/components/Modal';
import { MyTreeSelect, MyTreeProps } from '/@/components/BizTreeSelect';
import { useModal } from '/@/components/Modal';
import { listDataGroupTree } from '/@/api/infra/dataGroup'
import MaterialList from './components/MaterialList.vue'
import { MaterialType } from './material.data'
import MeterialGroupModal from './components/MeterialGroupModal.vue'
import { propTypes } from '/@/utils/propTypes';
import { PageWrapper } from '/@/components/Page';
import { DataGroupBizType } from '/@/components/BizDataGroup/index';
import { deleteGroup } from '/@/api/infra/material';
import { useAttrs } from '/@/hooks/core/useAttrs';
import { useAppProviderContext } from '/@/components/Application';
const attrs = useAttrs({ excludeDefaultKeys: false });

const namespace = useAppProviderContext().prefixCls
// 声明Emits
const emit = defineEmits(['register', 'success', 'select-change']);

const props = defineProps({
  // 素材类型
  materialType: propTypes.string,
  // 可以选择的数量
  selectCount: propTypes.number.def(1)
});

const treeProps = ref<MyTreeProps>({
  searchField: 'name',
  api: listDataGroupTree,
  immediate: true,
  params: {
    bizType: DataGroupBizType.MATERIAL,
    groupType: MaterialType.IMAGE.type
  },
  enableAddChird: true,
  enableDelete: true,
  enableEdit: true,
  deleteApi: deleteGroup
})

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {

});

const title = computed(() => {
  for (const key in MaterialType) {
    if (props.materialType === MaterialType[key].type) {
      return `选择${MaterialType[key].name}`
    }
  }
  return `选择素材`
});

let timer = null
const activeMaterialType = ref(MaterialType.IMAGE.type)
const materialGroupTreeRef = ref<any>()
const slectedRows = ref<any[]>([])
const [registerMeterialGroup, { openModal: openMeterialGroupModal }] = useModal();
const { prefixCls } = useDesign('material')
provide('prefixCls', prefixCls)

// 当前选中的分组
let materialGroupId = ref()

onMounted(() => {
  
})
watchEffect(() => {
  if (props.materialType) {
    activeMaterialType.value = props.materialType
    treeProps.value.params = {
      groupType: props.materialType,
      bizType: DataGroupBizType.MATERIAL,
    }
    materialGroupTreeRef.value.reload()
  }
  console.log('-------------------------', props);
})

const handleChange = async (e) => {
  console.log('tab: ', e);
  clearTimeout(timer)
  timer = null
  // 避免切换tab卡顿
  timer = setTimeout(() => {
    activeMaterialType.value = e
    treeProps.value.params.groupType = e
  }, 200)
}

// 左侧树选择后触发
function onTreeSelect(data) {
  console.log('onTreeSelect', data);
  materialGroupId.value = data
}

const handleOpenGroup = (materialType) => {
  openMeterialGroupModal(true, {
    isUpdate: false,
    materialType
  })
}

const handleAddGroup = (node) => {
  openMeterialGroupModal(true, {
    isUpdate: false,
    materialType: activeMaterialType.value,
    record: { parentId: node.id }
  }
  )
}

const handleEditGroup = (node) => {
  openMeterialGroupModal(true, {
    isUpdate: true,
    materialType: activeMaterialType.value,
    record: {
      ...node,
      name: node.title
    }
  })
}

const handleSaveOrUpdateGroupSuccess = () => materialGroupTreeRef.value.reload()

onUnmounted(() => {
  clearTimeout(timer)
  timer = null
})

const handleSelectChange = (rows) => slectedRows.value = rows

async function handleSubmit(v) {
  closeModal();
  emit('select-change', unref(slectedRows))
}
</script>

<style lang="less"></style>